<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>生产计划实时监控</title>
    <script src="https://cdn.jsdelivr.net/npm/@microsoft/signalr@7.0.0/dist/browser/signalr.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background-color: #f5f5f5;
            padding: 20px;
        }
        .container {
            max-width: 1400px;
            margin: 0 auto;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        h1 {
            font-size: 28px;
            margin-bottom: 10px;
        }
        .status-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 15px;
        }
        .status-badge {
            padding: 8px 16px;
            border-radius: 20px;
            font-weight: bold;
            font-size: 14px;
        }
        .status-badge.connected {
            background-color: #d4edda;
            color: #155724;
        }
        .status-badge.disconnected {
            background-color: #f8d7da;
            color: #721c24;
        }
        .controls button {
            background-color: white;
            color: #667eea;
            padding: 10px 20px;
            border: 2px solid white;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            margin-left: 10px;
            font-weight: bold;
        }
        .controls button:hover:not(:disabled) {
            background-color: #f0f0f0;
        }
        .controls button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        .content {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 20px;
        }
        .panel {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .panel h2 {
            color: #333;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #667eea;
        }
        .table-container {
            overflow-x: auto;
            max-height: 600px;
            overflow-y: auto;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
        }
        th {
            background-color: #667eea;
            color: white;
            padding: 12px 8px;
            text-align: left;
            position: sticky;
            top: 0;
            z-index: 10;
        }
        td {
            padding: 10px 8px;
            border-bottom: 1px solid #eee;
        }
        tr:hover {
            background-color: #f9f9f9;
        }
        .empty {
            text-align: center;
            color: #999;
            padding: 40px;
        }
        .message-list {
            max-height: 600px;
            overflow-y: auto;
        }
        .message-item {
            padding: 12px;
            margin-bottom: 10px;
            background: #f9f9f9;
            border-left: 4px solid #667eea;
            border-radius: 4px;
        }
        .message-item.equipment {
            border-left-color: #4CAF50;
        }
        .message-item.error {
            border-left-color: #f44336;
            background: #ffebee;
        }
        .message-time {
            color: #666;
            font-size: 0.9em;
            margin-bottom: 5px;
        }
        .message-type {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 3px;
            font-size: 0.85em;
            font-weight: bold;
            margin-right: 8px;
        }
        .message-type.production {
            background-color: #e3f2fd;
            color: #1976d2;
        }
        .message-type.equipment {
            background-color: #e8f5e9;
            color: #388e3c;
        }
        .message-type.error {
            background-color: #ffebee;
            color: #c62828;
        }
        .message-type.order {
            background-color: #fff3e0;
            color: #e65100;
        }
        .stats {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 15px;
            margin-bottom: 20px;
        }
        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px;
            border-radius: 8px;
            text-align: center;
        }
        .stat-value {
            font-size: 32px;
            font-weight: bold;
            margin: 10px 0;
        }
        .stat-label {
            font-size: 14px;
            opacity: 0.9;
        }
        .last-update {
            text-align: center;
            color: #666;
            font-size: 14px;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📊 生产计划实时监控系统</h1>
            <div class="status-bar">
                <div id="connectionStatus" class="status-badge disconnected">
                    ⚠️ 未连接
                </div>
                <div class="controls">
                    <button id="connectBtn" onclick="connect()">连接服务器</button>
                    <button id="disconnectBtn" onclick="disconnect()" disabled>断开连接</button>
                </div>
            </div>
        </div>

        <div class="stats">
            <div class="stat-card">
                <div class="stat-label">总计划数</div>
                <div class="stat-value" id="totalCount">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">设备更新次数</div>
                <div class="stat-value" id="equipmentUpdateCount">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">计划更新次数</div>
                <div class="stat-value" id="scheduleUpdateCount">0</div>
            </div>
        </div>

        <div class="content">
            <div class="panel">
                <h2>📋 生产计划列表</h2>
                <div id="lastUpdate" class="last-update">等待数据...</div>
                <div class="table-container">
                    <table id="productionTable">
                        <thead>
                            <tr>
                                <th>排程编号</th>
                                <th>工序名称</th>
                                <th>产品名称</th>
                                <th>设备名称</th>
                                <th>负责人</th>
                                <th>计划开始</th>
                                <th>计划结束</th>
                                <th>订单数量</th>
                            </tr>
                        </thead>
                        <tbody id="productionTableBody">
                            <tr>
                                <td colspan="8" class="empty">等待接收数据...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="panel">
                <h2>📢 更新日志</h2>
                <div id="messages" class="message-list">
                    <p class="empty">等待接收消息...</p>
                </div>
            </div>
        </div>
    </div>

    <script>
        let connection = null;
        let equipmentUpdateCount = 0;
        let scheduleUpdateCount = 0;

        async function connect() {
            try {
                connection = new signalR.HubConnectionBuilder()
                    .withUrl("/equipmentStatusHub")
                    .withAutomaticReconnect()
                    .configureLogging(signalR.LogLevel.Information)
                    .build();

                // 监听生产计划更新
                connection.on("ReceiveProductionScheduleUpdate", (data) => {
                    console.log("收到生产计划更新:", data);
                    scheduleUpdateCount++;
                    document.getElementById("scheduleUpdateCount").textContent = scheduleUpdateCount;
                    updateProductionTable(data);
                    addMessage(data, "production");
                });

                // 监听设备状态更新
                connection.on("ReceiveEquipmentStatusUpdate", (data) => {
                    console.log("收到设备状态更新:", data);
                    equipmentUpdateCount++;
                    document.getElementById("equipmentUpdateCount").textContent = equipmentUpdateCount;
                    addMessage(data, "equipment");
                });

                // 监听自动创建订单消息
                connection.on("ReceiveAutoOrderCreated", (data) => {
                    console.log("收到自动创建订单消息:", data);
                    addMessage(data, "order");
                });

                // 监听自动创建订单错误消息
                connection.on("ReceiveAutoOrderError", (data) => {
                    console.error("自动创建订单错误:", data);
                    addMessage(data, "error");
                });

                // 监听错误消息
                connection.on("ReceiveProductionScheduleError", (data) => {
                    console.error("生产计划错误:", data);
                    addMessage(data, "error");
                });

                // 连接状态变化
                connection.onreconnecting(() => {
                    updateStatus("reconnecting", "🔄 正在重新连接...");
                });

                connection.onreconnected(() => {
                    updateStatus("connected", "✅ 已重新连接");
                });

                connection.onclose(() => {
                    updateStatus("disconnected", "⚠️ 连接已断开");
                    document.getElementById("connectBtn").disabled = false;
                    document.getElementById("disconnectBtn").disabled = true;
                });

                await connection.start();
                console.log("SignalR 连接成功");
                updateStatus("connected", "✅ 已连接到服务器");
                document.getElementById("connectBtn").disabled = true;
                document.getElementById("disconnectBtn").disabled = false;

            } catch (err) {
                console.error("连接失败:", err);
                updateStatus("disconnected", "❌ 连接失败: " + err.message);
            }
        }

        async function disconnect() {
            if (connection) {
                await connection.stop();
                console.log("SignalR 连接已断开");
            }
        }

        function updateStatus(status, message) {
            const statusDiv = document.getElementById("connectionStatus");
            statusDiv.className = "status-badge " + (status === "connected" ? "connected" : "disconnected");
            statusDiv.textContent = message;
        }

        function updateProductionTable(data) {
            const tbody = document.getElementById("productionTableBody");
            const totalCountEl = document.getElementById("totalCount");
            const lastUpdateEl = document.getElementById("lastUpdate");

            if (!data.Data || data.Data.length === 0) {
                tbody.innerHTML = '<tr><td colspan="8" class="empty">暂无数据</td></tr>';
                totalCountEl.textContent = "0";
                return;
            }

            totalCountEl.textContent = data.TotalCount || data.Data.length;
            lastUpdateEl.textContent = `最后更新: ${new Date(data.Time).toLocaleString('zh-CN')}`;

            tbody.innerHTML = data.Data.map(item => `
                <tr>
                    <td>${item.Plannumber || '-'}</td>
                    <td>${item.Processname || '-'}</td>
                    <td>${item.Goodsname || '-'}</td>
                    <td>${item.Equipmentname || '-'}</td>
                    <td>${item.Manager || '-'}</td>
                    <td>${formatDateTime(item.Planstatetime)}</td>
                    <td>${formatDateTime(item.Planendtime)}</td>
                    <td>${item.OrderNumber || 0}</td>
                </tr>
            `).join('');
        }

        function addMessage(data, type) {
            const messagesDiv = document.getElementById("messages");
            
            if (messagesDiv.querySelector('.empty')) {
                messagesDiv.innerHTML = '';
            }

            const messageDiv = document.createElement("div");
            messageDiv.className = `message-item ${type}`;
            
            const time = data.Time ? new Date(data.Time).toLocaleString('zh-CN') : new Date().toLocaleString('zh-CN');
            const typeLabels = {
                'production': '生产计划',
                'equipment': '设备状态',
                'order': '自动订单',
                'error': '错误'
            };
            const typeLabel = typeLabels[type] || '未知';
            
            let content = data.Message || JSON.stringify(data);
            
            // 如果是订单消息，添加详细信息
            if (type === 'order' && data.Itemname) {
                content += `<br><small>成品: ${data.Itemname}, 数量: ${data.Number}</small>`;
            }
            
            messageDiv.innerHTML = `
                <div class="message-time">
                    <span class="message-type ${type}">${typeLabel}</span>
                    ⏰ ${time}
                </div>
                <div class="message-content">${content}</div>
            `;
            
            messagesDiv.insertBefore(messageDiv, messagesDiv.firstChild);

            while (messagesDiv.children.length > 50) {
                messagesDiv.removeChild(messagesDiv.lastChild);
            }
        }

        function formatDateTime(dateStr) {
            if (!dateStr) return '-';
            const date = new Date(dateStr);
            return date.toLocaleString('zh-CN', {
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        window.addEventListener('load', () => {
            console.log("页面已加载，准备连接SignalR...");
            // 自动连接
            connect();
        });
    </script>
</body>
</html>
